const express = require('express');
const path = require('path');
// const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const date_tool = require('./util/date_tool');

let app = express();

const version = 'v1.2.16';

// 路由管理
const users_router = require('./routes/users');
const stat_router = require('./routes/stat');
const student_router = require('./routes/student');
const harm_router = require('./routes/harm');
const consult_router = require('./routes/consult');
const sicken_router = require('./routes/sicken');
const interview_router = require('./routes/interview');
const census_router = require('./routes/census');
const import_router = require('./routes/import');
const classes_router = require('./routes/classes');
const file_router = require('./routes/file');

// 输出所有请求的日志
app.use(function (req, res, next) {
    // 记录请求到达服务端的时间戳
    req.time = new Date();
    req.formatTime = date_tool.formatDate(req.time);
    // 输出请求的日志 - 如果使用了反向代理 此处的地址可能不是客户端的 需要修改
    console.log(`${req.connection.remoteAddress} | ${req.formatTime} | ${req.method} ${req.originalUrl} | `);
    next();
});

// 设置允许跨域请求
app.use(function (req, res, next) {
    // 添加允许跨域的请求头
    // 设置允许跨域的源为所有源
    res.setHeader('Access-Control-Allow-Origin', '*');
    // 设置允许的HTTP方法为所有方法
    res.setHeader('Access-Control-Allow-Methods', '*');
    // 设置允许的请求头为所有头
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 解决预检请求
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
        return;
    }
    // 进行下一个路由的调用
    next();
});

// 设置http请求报文的长度限制为 15M
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

// 服务端解析json数据的中间件
app.use(express.json());
// 服务端解析GET请求参数的中间件
app.use(express.urlencoded({ extended: false }));
// 服务端解析cookie的中间件（暂时不使用）
// app.use(cookieParser());

// 挂载静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 添加代码版本信息接口，用于每次启动服务时用于检查更新
app.get('/version', function (req, res, next) {
    res.status(200).json({
        success: true,
        msg: '获取版本号成功',
        data: {
            version: version
        }
    });
});

// 动态路由
app.use('/users', users_router);
app.use('/stat', stat_router);
app.use('/student', student_router);
app.use('/harm', harm_router);
app.use('/consult', consult_router);
app.use('/sicken', sicken_router);
app.use('/interview', interview_router);
app.use('/census', census_router);
app.use('/import', import_router);
app.use('/class', classes_router);
app.use('/file', file_router);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    // res.send('404 Not Found');
    res.status(404);
    res.statusMessage = '404 not found';
    res.sendFile(path.join(__dirname, '/views/error.html'))
});

// app对象暴露
module.exports = app;
